package com.android.kotlincoroutinemvvmdemo.view
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapShader
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Shader
import android.util.AttributeSet
import android.view.View
import com.android.kotlincoroutinemvvmdemo.R
import com.android.kotlincoroutinemvvmdemo.decodeSampledBitmapFromResource

class DiCircleImageView @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null
) : View(context, attributeSet) {

    private var mWidth = 0
    private var mHeight = 0

    private val mPaint0 by lazy {
        Paint().apply {
            isAntiAlias = true
            isDither = true
            color = context.resources.getColor(R.color.color_ff5722)
            style = Paint.Style.FILL
        }
    }

    private var mBitmap0: Bitmap? = null
    private var mBitmapShader: BitmapShader? = null

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        mWidth = when(MeasureSpec.getMode(widthMeasureSpec)) {
            MeasureSpec.EXACTLY -> {
                MeasureSpec.getSize(widthMeasureSpec)
            }
            else -> {
                context.resources.getDimension(R.dimen.dp_100).toInt()
            }
        } - paddingStart - paddingEnd

        mHeight = when(MeasureSpec.getMode(heightMeasureSpec)) {
            MeasureSpec.EXACTLY -> {
                MeasureSpec.getSize(heightMeasureSpec)
            }
            else -> {
                context.resources.getDimension(R.dimen.dp_100).toInt()
            }
        } - paddingTop - paddingBottom

        setMeasuredDimension(mWidth, mHeight)

        if (mBitmap0 == null) {
            mBitmap0 = decodeSampledBitmapFromResource(resources, R.drawable.p10, mWidth, mHeight)
        }

        if (mBitmapShader == null) {
            mBitmapShader = BitmapShader(mBitmap0!!, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
        }

        mPaint0.shader = mBitmapShader
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.apply {
            translate(mWidth / 2.0F, mHeight / 2.0F)
            //圆形
            drawCircle(0F, 0F, mWidth / 2.0F - resources.getDimension(R.dimen.dp_2), mPaint0)
            //矩形,三角形.....
        }
    }

    companion object {
        const val TAG = "DiCircleImageView"
    }
}